package org.fastsyncer.connector.oracle;

import org.fastsyncer.common.entity.BaseInfo;
import org.fastsyncer.common.entity.DatabaseConfig;
import org.fastsyncer.connector.common.DatabaseConstant;
import org.fastsyncer.connector.framework.AbstractDatabaseConnector;
import org.fastsyncer.connector.util.DatabaseUtil;
import org.springframework.jdbc.core.JdbcTemplate;

public final class OracleConnector extends AbstractDatabaseConnector {

    private static volatile OracleConnector instance = null;

    private OracleConnector() {
    }

    public static OracleConnector getInstance() {
        if (null == instance) {
            synchronized (OracleConnector.class) {
                if (null == instance) {
                    instance = new OracleConnector();
                }
            }
        }
        return instance;
    }

    @Override
    public BaseInfo getBaseInfoConnector(DatabaseConfig config, String queryFilter) {
        JdbcTemplate jdbcTemplate = this.getJdbcTemplate(config);
        String table = config.getTable().toUpperCase();
        // 查询元信息 SELECT * FROM USER WHERE ROWNUM = 0
        String metaSQL = new StringBuilder().append("SELECT * FROM ").append(table).append(" WHERE").append(DatabaseConstant.ORACLE_PAGE_SQL_NULL).toString();
        // 求数据总量 SELECT * FROM USER WHERE ID='123'
        String countSQL = new StringBuilder().append("SELECT * FROM ").append(table).append(queryFilter).toString();
        BaseInfo connector = DatabaseUtil.getDataSourceConnector(jdbcTemplate, metaSQL, countSQL);
        // 释放连接
        this.close(jdbcTemplate);
        return connector;
    }

    @Override
    public StringBuilder getPageSQL(DatabaseConfig config, StringBuilder sql) {
        // Oracle 分页查询
        sql.insert(0, DatabaseConstant.ORACLE_PAGE_SQL_START);
        sql.append(DatabaseConstant.ORACLE_PAGE_SQL_END);
        return sql;
    }

}
